package net.maku.events.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import lombok.AllArgsConstructor;
import net.maku.events.dao.UserAnswerQuestionTimeDao;
import net.maku.events.entity.UserAnswerQuestionTimeEntity;
import net.maku.events.service.UserAnswerQuestionTimeService;
import net.maku.framework.mybatis.service.impl.BaseServiceImpl;
import net.maku.framework.security.user.SecurityUser;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Author: qr
 * @Date: 2025/4/20 9:48
 * @Version 1.0
 */
@Service
@AllArgsConstructor
public class UserAnswerQuestionTimeServiceImpl extends BaseServiceImpl<UserAnswerQuestionTimeDao, UserAnswerQuestionTimeEntity> implements UserAnswerQuestionTimeService {


    @Override
    public void insertUserAnswerQuestion(Long businessId, Long businessSonId, Integer businessType) {
        List<UserAnswerQuestionTimeEntity> checkEntityList = this.list(new LambdaQueryWrapper<UserAnswerQuestionTimeEntity>().eq(UserAnswerQuestionTimeEntity::getBusinessType, businessType)
                .eq(UserAnswerQuestionTimeEntity::getBusinessId, businessId)
                .eq(UserAnswerQuestionTimeEntity::getUserId, SecurityUser.getUserId())
                .eq(ObjectUtils.isNotEmpty(businessSonId), UserAnswerQuestionTimeEntity::getBusinessSonId, businessSonId)
                .isNull(UserAnswerQuestionTimeEntity::getAnswerTime));
        if (CollectionUtils.isNotEmpty(checkEntityList)) {
            return;
        }
        UserAnswerQuestionTimeEntity newEntity = new UserAnswerQuestionTimeEntity().setUserId(SecurityUser.getUserId())
                .setBusinessType(businessType)
                .setBusinessId(businessId)
                .setBusinessSonId(businessSonId);
        this.save(newEntity);
    }

    @Override
    public void completedUserAnswerQuestion(Long businessId, Long businessSonId, Integer businessType) {
        this.update(new LambdaUpdateWrapper<UserAnswerQuestionTimeEntity>()
                .eq(UserAnswerQuestionTimeEntity::getUserId, SecurityUser.getUserId())
                .eq(UserAnswerQuestionTimeEntity::getBusinessType, businessType)
                .eq(UserAnswerQuestionTimeEntity::getBusinessId, businessId)
                .eq(ObjectUtils.isNotEmpty(businessSonId), UserAnswerQuestionTimeEntity::getBusinessSonId, businessSonId)
                .set(UserAnswerQuestionTimeEntity::getAnswerTime, new Date()));
    }
}
